package com.biglead.demo.controller;



import com.biglead.demo.common.R;
import com.biglead.demo.service.GoodsService;
import com.biglead.demo.vo.GoodsVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Api(tags="商品模块")
@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 商品列表
     * @return
     */
    @GetMapping("/toList")
    public R toList(){
        // 缓存商品信息
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<GoodsVo> goodsList = (List<GoodsVo>) valueOperations.get("goodsList");
        if (!Objects.isNull(goodsList)) {
            return R.okData(goodsList);
        }

        List<GoodsVo> goodsVoList = goodsService.findGoodsVo();
        valueOperations.set("goodsList", goodsVoList);
        // 1小时的有效时间
        valueOperations.set("goodsList", goodsVoList, 10*60*60, TimeUnit.SECONDS);
        return R.okData(goodsVoList);
    }

    /**
     * 获取商品详情
     * @param goodsId
     * @return
     */
    @GetMapping("/toDetail/{id}")
    public R toDetail(@PathVariable("id") Long goodsId) {
        // URL 缓存
        ValueOperations valueOperations = redisTemplate.opsForValue();
        GoodsVo goodsDetail = (GoodsVo) valueOperations.get("goodsDetail:" + goodsId);
        if (!Objects.isNull(goodsDetail)) {
            return R.okData(goodsDetail);
        }

        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
        // 1小时的有效时间
        valueOperations.set("goodsDetail:" + goodsId, goodsVo, 10*60*60, TimeUnit.SECONDS);
        return R.okData(goodsVo);
    }

}
